/*
 * j4Win
 *  http://code.google.com/p/j4win/
 *
 * Copyright (C) 2006-2007 Felix Geyer, Moritz Laschinger
 *
 * This file is part of j4Win.
 *
 * j4Win is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * j4Win is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package j4win;

import java.awt.EventQueue;
import java.util.concurrent.locks.ReentrantLock;

public abstract class KI {
	private PlayerListener listener;
	protected Field field;
	protected int lastCol;
	
	public KI() {
		thread.start();
	}
	
	public void requestMove(Field field, PlayerListener listener, int lastCol) {
		this.field = field;
		this.listener = listener;
		this.lastCol = lastCol;
		
		startLock.lock();
		start = true;
		startLock.unlock();
	}
	
	protected abstract void requestMove();
	
	protected void move(int col) {
		moveCol = col;
		EventQueue.invokeLater(kiMove);
	}
	
	private Runnable kiMove = new Runnable() {
		public void run() {
	    	listener.move(moveCol);
		}
	};
	
	@Override
	protected void finalize() {
		stop();
	}
	
	public void stop() {
		stopLock.lock();
		stop = true;
		stopLock.unlock();
	}
	
	private boolean start = false;
	private boolean stop = false;
	private int moveCol;
	
	private ReentrantLock startLock = new ReentrantLock();
	private ReentrantLock stopLock = new ReentrantLock();
	
	private Thread thread = new Thread() {
		@Override
		public void run() {
			boolean st, sp;
			while (true) {
				startLock.lock();
				st = start;
				if (start) start = false;
				startLock.unlock();
				
				if (st) {
					requestMove();
				}
				
				stopLock.lock();
				sp = stop;
				stopLock.unlock();
				if (sp) break;
				
				try {
					sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	};
}
